<template>
  <div class="exam-container">
    <h2 class="title">在线考试</h2>

    <!-- 显示考试信息 -->
    <div v-if="exam" class="exam-info">
      <h1>{{ exam.name }}</h1>
      <p>{{ exam.description }}</p>
      <p class="exam-id">考试ID: {{ exam.id }}</p>
    </div>

    <div class="exam-content">
      <!-- 显示题目 -->
      <div class="exam-questions">
        <div
            v-for="(question, index) in examQuestions"
            :key="question.id"
            class="exam-question"
            :ref="`question-${index}`"
        >
          <div class="question-header">
            <span class="question-number">{{ index + 1 }}.</span>
            <span class="question-text">{{ question.questionText }}</span>
            <!-- 标注题目类型 -->
            <span class="question-type">
              {{ question.questionType === '单选' ? '单选' : '多选' }}
            </span>
          </div>

          <!-- 单选题 -->
          <div v-if="question.questionType === '单选'">
            <el-radio-group v-model="answers[index]" class="radio-group">
              <el-radio :label="'A'" class="radio-option">{{ question.option1 }}</el-radio>
              <el-radio :label="'B'" class="radio-option">{{ question.option2 }}</el-radio>
              <el-radio :label="'C'" class="radio-option">{{ question.option3 }}</el-radio>
              <el-radio :label="'D'" class="radio-option">{{ question.option4 }}</el-radio>
            </el-radio-group>
          </div>

          <!-- 多选题 -->
          <div v-if="question.questionType === '多选'">
            <el-checkbox-group v-model="answers[index]" class="checkbox-group">
              <el-checkbox :label="'A'" class="checkbox-option">{{ question.option1 }}</el-checkbox>
              <el-checkbox :label="'B'" class="checkbox-option">{{ question.option2 }}</el-checkbox>
              <el-checkbox :label="'C'" class="checkbox-option">{{ question.option3 }}</el-checkbox>
              <el-checkbox :label="'D'" class="checkbox-option">{{ question.option4 }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>

      <!-- 显示题号 -->
      <div class="question-numbers">
        <h3>题号</h3>
        <div class="question-numbers-grid">
          <div
              v-for="(question, index) in examQuestions"
              :key="question.id"
              @click="scrollToQuestion(index)"
              class="question-number-item"
          >
            {{ index + 1 }}
          </div>
        </div>
      </div>
    </div>

    <!-- 计时器 -->
    <div class="timer">
      <span>剩余时间：{{ remainingTime }}秒</span>
    </div>

    <!-- 提交按钮 -->
    <el-button type="primary" class="submit-btn" @click="submitExam">提交考试</el-button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from '@/utiles/axios';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

const exam = ref(null);
const examQuestions = ref([]);
const answers = ref([]);  // 存储答案，单选题是字符串，多选题是数组
const remainingTime = ref(600);

const studentId = localStorage.getItem('studentId');
const trainingPlanId = route.params.trainingPlanId;  // 获取培训计划ID
const examId = ref();  // 获取 examId 参数
const examRecordId = ref(null);

// 获取考试信息和题目
const getExam = async () => {
  try {
    const examRes = await axios.get(`/exams/trainingPlan/${trainingPlanId}`);
    if (examRes.data && examRes.data.id) {
      exam.value = examRes.data;
      examId.value = exam.value.id;
    } else {
      console.error('获取考试数据失败，数据格式不正确');
    }

    // 获取题目列表
    const questionsRes = await axios.get(`/exams/${examId.value}/questions`);
    examQuestions.value = questionsRes.data;

    const examRecordRes = await axios.post(`/exams/start/${studentId}/${examId.value}`);
    examRecordId.value = examRecordRes.data.id;
  } catch (error) {
    console.error('获取考试数据失败', error);
  }
};

// 提交答案
const submitExam = async () => {
  try {
    const recordId = Number(examRecordId.value);
    if (isNaN(recordId)) {
      console.error('无效的考试记录ID');
      return;
    }

    // 转换多选题的答案为字符串形式 "A,B"
    const formattedAnswers = answers.value.map(answer => {
      if (Array.isArray(answer)) {
        return answer.join(',');  // 将数组转为逗号分隔的字符串
      }
      return answer;
    });

    // 提交答案
    await axios.post(`/exams/submit/${recordId}`, formattedAnswers);
    alert('考试提交成功');
    await router.push({ path: `/exam-result/${recordId}`, query: { trainingPlanId } });
  } catch (error) {
    console.error('提交失败', error);
  }
};

// 启动倒计时
const startTimer = () => {
  const timer = setInterval(() => {
    if (remainingTime.value <= 0) {
      clearInterval(timer);
      submitExam();  // 超过时间自动提交
    } else {
      remainingTime.value--;
    }
  }, 1000);
};

// 滚动到指定题目
const scrollToQuestion = (index) => {
  const questionElement = document.querySelector(`.exam-question:nth-child(${index + 1})`);
  if (questionElement) {
    questionElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
};

onMounted(() => {
  getExam();
  startTimer();
});
</script>

<style scoped>
.exam-container {
  max-width: 1000px;
  margin: 50px auto;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-family: 'Arial', sans-serif;
}

.title {
  text-align: center;
  font-size: 2em;
  color: #333;
  margin-bottom: 30px;
}

.exam-info {
  background: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.exam-id {
  color: #999;
}

.exam-content {
  display: flex;
  justify-content: space-between;
}

.exam-questions {
  width: 75%;
}

.question-header {
  display: flex;
  align-items: center;
  font-size: 1.2em;
  margin-bottom: 15px;
}

.question-number {
  font-weight: bold;
  margin-right: 10px;
  color: #007BFF;
}

.question-text {
  flex-grow: 1;
}

.question-type {
  font-size: 1em;
  margin-left: 20px;
  color: #FF5733;
  font-weight: bold;
}

.radio-group, .checkbox-group {
  display: block;
  margin-top: 10px;
}

.radio-option, .checkbox-option {
  display: block;
  margin: 5px 0;
  text-align: left;
  padding-left: 20px;
}

.question-numbers {
  width: 20%;
  padding-left: 20px;
}

.question-numbers-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 每行5个 */
  gap: 10px;
}

.question-number-item {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15px;
  background-color: #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.2em;
  text-align: center;
  transition: background-color 0.3s, transform 0.3s;
}

.question-number-item:hover {
  background-color: #007BFF;
  color: #fff;
  transform: scale(1.1);
}

.timer {
  text-align: center;
  font-size: 1.5em;
  color: #FF5733;
  margin-top: 20px;
}

.submit-btn {
  display: block;
  width: 100%;
  margin-top: 30px;
  font-size: 1.2em;
  padding: 10px;
}

.submit-btn:hover {
  background-color: #0056b3;
}

.submit-btn:focus {
  outline: none;
}
</style>
